#!/usr/bin/env python3
"""
Gitee Release文件上传脚本 - 修复版
"""

import argparse
import os
import requests
import json
import sys


def gitee_upload_to_release(
    file_path,
    owner,
    repo,
    access_token,
    tag_name,
    release_name=None,
    body=None,
    target_commitish=None,
    draft=False,
    prerelease=False,
):
    """
    将文件上传到Gitee仓库的特定发行版
    """

    if not os.path.exists(file_path):
        print(f"错误：文件 '{file_path}' 不存在")
        sys.exit(1)

    headers = {
        "Content-Type": "application/json;charset=UTF-8",
        "User-Agent": "Gitee-Release-Upload-Script/1.0",
    }

    base_url = "https://gitee.com/api/v5"

    # 1. 检查发行版是否存在
    check_release_url = f"{base_url}/repos/{owner}/{repo}/releases/tags/{tag_name}"
    params = {"access_token": access_token}

    print(f"检查发行版是否存在: {tag_name}")
    response = requests.get(check_release_url, params=params, headers=headers)

    release_id = None
    if response.status_code == 200:
        try:
            release_data = response.json()
            if release_data and "id" in release_data:
                release_id = release_data["id"]
                print(
                    f"找到已存在的发行版: {release_data.get('name', 'Unknown')} (ID: {release_id})"
                )
            else:
                print("发行版不存在或数据不完整，将创建新发行版")
                release_id = None
        except (json.JSONDecodeError, KeyError) as e:
            print(f"解析发行版数据时出错: {e}")
            release_id = None
    elif response.status_code == 404:
        print(f"发行版 '{tag_name}' 不存在")
        release_id = None
    else:
        print(f"检查发行版时出错！状态码: {response.status_code}")
        print(f"错误信息: {response.text}")
        release_id = None

    # 如果发行版不存在，创建新发行版
    if release_id is None:
        print("创建新发行版...")
        create_release_url = f"{base_url}/repos/{owner}/{repo}/releases"

        release_data = {
            "access_token": access_token,
            "tag_name": tag_name,
            "name": release_name or tag_name,
            "body": body or f"Release {tag_name}",
            "target_commitish": target_commitish,
            "draft": draft,
            "prerelease": prerelease,
        }

        release_data = {k: v for k, v in release_data.items() if v is not None}

        response = requests.post(create_release_url, json=release_data, headers=headers)

        if response.status_code == 201:
            try:
                release_info = response.json()
                release_id = release_info["id"]
                print(
                    f"成功创建发行版: {release_info.get('name', 'Unknown')} (ID: {release_id})"
                )
            except (json.JSONDecodeError, KeyError) as e:
                print(f"解析创建响应时出错: {e}")
                sys.exit(1)
        else:
            print(f"创建发行版失败！状态码: {response.status_code}")
            print(f"错误信息: {response.text}")
            sys.exit(1)

    # 2. 上传文件到发行版
    print(f"开始上传文件: {os.path.basename(file_path)}")

    upload_url = f"{base_url}/repos/{owner}/{repo}/releases/{release_id}/attach_files"

    try:
        with open(file_path, "rb") as file:
            files = {
                "file": (os.path.basename(file_path), file, "application/octet-stream")
            }

            data = {"access_token": access_token}

            upload_response = requests.post(upload_url, data=data, files=files)

            if upload_response.status_code == 201:
                upload_result = upload_response.json()
                print("✅ 文件上传成功！")
                print(f"📄 文件名: {upload_result.get('name', 'Unknown')}")
                print(f"📊 文件大小: {upload_result.get('size', 'Unknown')} 字节")
                print(
                    f"🔗 下载URL: {upload_result.get('browser_download_url', 'Unknown')}"
                )
                return upload_result
            else:
                print(f"❌ 文件上传失败！状态码: {upload_response.status_code}")
                print(f"错误信息: {upload_response.text}")
                sys.exit(1)

    except Exception as e:
        print(f"❌ 上传文件时发生异常: {e}")
        sys.exit(1)


def main():
    parser = argparse.ArgumentParser(description="上传文件到Gitee仓库的发行版")
    parser.add_argument("file_path", type=str, help="要上传的本地文件路径")
    parser.add_argument(
        "--owner", type=str, required=True, help="Gitee仓库所有者用户名"
    )
    parser.add_argument("--repo", type=str, required=True, help="Gitee仓库名")
    parser.add_argument("--token", type=str, required=True, help="Gitee私人令牌")
    parser.add_argument("--tag", type=str, required=True, help="发行版标签名")
    parser.add_argument("--name", type=str, help="发行版名称")
    parser.add_argument("--body", type=str, help="发行版说明")
    parser.add_argument("--branch", type=str, help="目标分支")
    parser.add_argument("--draft", action="store_true", help="创建为草稿版")
    parser.add_argument("--prerelease", action="store_true", help="创建为预发行版")

    args = parser.parse_args()

    gitee_upload_to_release(
        file_path=args.file_path,
        owner=args.owner,
        repo=args.repo,
        access_token=args.token,
        tag_name=args.tag,
        release_name=args.name,
        body=args.body,
        target_commitish=args.branch,
        draft=args.draft,
        prerelease=args.prerelease,
    )


if __name__ == "__main__":
    main()
